import React, { Component } from 'react';
import axios from 'axios';
import './main.css';
import MenuHead from '../comm/menuHead';
import MenuBody from '../comm/menuBody';
import { connect } from 'react-redux';
import cookie from 'react-cookies';
import { page_query_action } from '../actions/pages';

class Main extends Component {
    state = {
        loginInfo: {
            curPage: "",
            curName: "",
            subPage: null,
            prtPage: null,
            userName: "",
            userRole: "",
            loginID: "",
            errorInfo: "",
        }
    }
    pageQuery = () => {
        let userName = cookie.load('login-name');
        let loginID = cookie.load('login-id');
        axios.post("/app/pageQuery", {
            "userName": userName,
            "curPage": "main",
            "loginID": loginID
        }).then((res) => {
            if("请先登录" === res.data.errorInfo) {
                this.props.history.push('/login');
            }
            this.props.pageQueryAction(res.data)
        }).catch((err) => {
            this.setState({error: "请求服务器端时产生的错误信息: " + err})
        })
    }
    componentDidMount() {
        if("" === this.props.loginInfo.curPage){
            this.pageQuery()
        }
    }
    logout = () => {
        axios.post("/app/logout", {
            "userName": this.props.loginInfo.userName,
            "loginID": this.props.loginInfo.loginID,
        }).then((res) => {
            if(res.data.loginStatus === false) {
                this.props.history.push('/login');
            } else {
                alert(res.data.errorInfo)
                console.log(res.data)
                this.setState(res.data)
            }
        }).catch((err) => {
            alert(err)
        })
    }
    render() {
        let curPage = this.props.loginInfo.curPage
        const mainHead = 'main' === curPage || '/' === curPage ? (
            <div className='headbar'>
                <div className='title'>小工具</div>
                <div className='logout'><span className='alink' onClick={this.logout}>注销</span></div>
            </div>
        ) : <MenuHead/>
        return (
            <div align="center">
                { mainHead }
                <MenuBody/>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return state;
}

const mapDispatchToProps = (dispatch) => {
    return {
        pageQueryAction: (loginInfo) => { dispatch(page_query_action(loginInfo)) }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Main);
